/*
 * @Author: huangkaicheng@rfchina.com
 * @Date: 2021-1-28 16:54:02
 * @LastEditTime: 2021-02-01 14:28:35
 * @LastEditors: huangkaicheng@rfchina.com
 * @Description: Compile LESS 2 Other
 * @FilePath: \rf-auto-jenkins-plugin\lib\lessCompile.js
 */
const fs = require("fs");
const path = require("path");
const less = require("less");
const chalk = require("chalk");

/**
 * @description:
 * @param  {*}
 * @return {*}
 * @param {*} rootPath  执行的当前路径
 * @param {*} filename  变动的less文件名
 * @param {*} nameSuffix  期待输出的文件后缀名
 */
function compileRoot(rootPath, filename, nameSuffix) {
  let filePath = path.join(rootPath, filename);
  let filePathWithoutSuffic = filePath.split(".")[0];
  // console.log('filePath',filePath);
  // console.log('filePathWithoutSuffic',filePathWithoutSuffic);
  //先读取less文件
  fileContent = fs
    .readFileSync(`${filePath}`, {
      encoding: "utf8",
    })
    .toString();
  //less提供的render方法，output
  console.log("filePath", filePath);
  let options = {
    javascriptEnabled: false,
    depends: false,
    compress: true, //开启压缩
    lint: false,
    paths: [rootPath],
    color: true,
    strictImports: false,
    insecure: false,
    rootpath: "",
    rewriteUrls: false,
    math: 1,
    strictUnits: false,
    globalVars: null,
    modifyVars: null,
    urlArgs: "",
    plugins: [],
    reUsePluginManager: true,
    filename: filePath,
  };
  less.render(fileContent, options).then(
    function (result) {
      fs.writeFile(
        `${filePathWithoutSuffic}.${nameSuffix}`,
        result.css,
        { encoding: "utf8" },
        (err) => {
          if (err) {
            return console.log(chalk.red(`failed to create file ' + ${err}`));
          } else {
            console.log(
              chalk.green(
                `sucess to compile ${filename} >>>>>>> ${filename.replace(
                  /.less/,
                  `.${nameSuffix}`
                )}`
              )
            );
          }
        }
      );
    },
    function (err) {
      if (!options.silent) {
        console.error(
          err.toString({
            stylize: options.color && less.lesscHelper.stylize,
          })
        );
      }
    }
  );
}
/**
 * @description:
 * @param  {*}
 * @return {*}
 * @param {*} rootPath
 * @param {*} nameSuffix
 */
function filterWatcher(rootPath, nameSuffix) {
  console.log(chalk.green(`start to watching the file!`));
  fs.watch(
    rootPath,
    {
      encoding: "utf-8",
      recursive: true, //是否监听子文件夹下面的文件变动情况
      persistent: true, //设置是否持续监听
    },
    (event, filename) => {
      //判断到变动并且文件是less后缀的话，就执行compileRoot编译方法
      if (event == "change" && path.extname(filename) === ".less") {
        compileRoot(rootPath, filename, nameSuffix);
      }
    }
  );
}
module.exports = filterWatcher;
